package model.handler;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import controller.GameConfig;

import main.Log;
import model.Executable;
import model.GameClock;
import model.entity.BasicEntity;
import model.entity.stats.StatSet;
import model.entity.stats.StatType;
import model.map.GameMap;
import model.map.World;
import utilities.*;

public class DeathHandler implements Archiveable {

	private static DeathHandler instance = null;

	private World world = World.getInstance();
	private GameMap gameMap = world.getCurrentMap();
	private List<BasicEntity> basicEntityList = gameMap.getEntities();
	private Executable ex;
	private long delay;

	public static DeathHandler getInstance() {
		if( instance != null ) { return instance; }
		return instance = new DeathHandler();
	}

	private DeathHandler() {
		// possibly add more to this later
		this.delay = 40;
	}

	public void start(){
		ex = new Executable(){
			public void execute() {
				wipeUpTheDeadMeat();
			}
		};
		GameClock.getInstance().scheduleAtFixedRate( delay, ex);
	} 

	public void stop(){
		if(ex == null){return ;}
		GameClock.getInstance().remove(ex);
	}

	private void wipeUpTheDeadMeat(){
		BasicEntity[] bel = new BasicEntity[basicEntityList.size()];
		basicEntityList.toArray(bel);
		for(int i=0; i < bel.length; i++) {
			//Log.out(Log.MODEL, "Health is:" + e.getStatVal(StatType.HP));
			if( bel[i].getStatVal(StatType.HP) <= 0 ){
				if( isAvatar(bel[i]) ){

					StatSet stats = bel[i].getStats();
					stats.addConstantModifier(StatType.LIVES, -1);
					if(stats.getStatVal(StatType.LIVES) < 0){
						//call a game over screen
						System.exit(1);
					}
				}
				else{
					gameMap.removeEntity(bel[i]);
					Random randGen = new Random();
					// lol
					if(bel[i].getInventory() != null){
						if(bel[i].getInventory().getItems().size() > 0){
							gameMap.addItem(bel[i].getLocation(), bel[i].getInventoryItems().get(randGen.nextInt(bel[i].getInventory().getItems().size())));
						}
						bel[i]=null;
					}
				}
			}
		}
	}

	private boolean isAvatar(BasicEntity e){
		if(e == world.getPlayer())
			return true;
		return false;
	}
	
	
	public Archive save() {
		Archive archive = ArchiveFactory.createArchive();
		
		archive.putAttribute("delay", Long.toString(this.delay));
		
		return archive;
	}
	
	public void load(Archive archive) {
		this.delay = Long.parseLong(archive.getAttribute("delay"));
	}
}
